package com.gy.smart.home;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.weather.LocalDayWeatherForecast;
import com.amap.api.services.weather.LocalWeatherForecast;
import com.amap.api.services.weather.LocalWeatherForecastResult;
import com.amap.api.services.weather.LocalWeatherLive;
import com.amap.api.services.weather.LocalWeatherLiveResult;
import com.amap.api.services.weather.WeatherSearch;
import com.amap.api.services.weather.WeatherSearchQuery;
import com.gy.smart.MyApplication;
import com.gy.smart.R;
import com.gy.smart.base.BaseBean;
import com.gy.smart.base.BaseFragment;
import com.gy.smart.handle.HandleListActivity;
import com.gy.smart.handle.HandleSelectActivity;
import com.gy.smart.handle.bean.HandleThemeBean;
import com.gy.smart.home.adapter.HomeHandleAdapter;
import com.gy.smart.home.adapter.HomeLifeAdapter;
import com.gy.smart.home.bean.HomeBean;
import com.gy.smart.home.bean.HomeNewsBean;
import com.gy.smart.home.view.HomeNewsView;
import com.gy.smart.life.LifeDetailActivity;
import com.gy.smart.life.LifeMapActivity;
import com.gy.smart.life.bean.LifeListBean;
import com.gy.smart.mine.MineActivity;
import com.gy.smart.util.AnimUtil;
import com.gy.smart.util.DeviceInfo;
import com.gy.smart.util.LocationManagers;
import com.gy.smart.util.LogUtil;
import com.gy.smart.util.RequestResultListener;
import com.gy.smart.util.StringConstants;
import com.gy.smart.util.Urls;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;

import org.xutils.http.RequestParams;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 高岳 on 2016/12/25.
 * Describe:首页
 */
public class HomeFragment extends BaseFragment implements LocationManagers.LocationChange,WeatherSearch.OnWeatherSearchListener{

    private PullToRefreshScrollView refreshScrollView;
    private LinearLayout llLoc,llHandle,llDynamic,llInteraction,llHelp,llNews;
    private ImageView imgPerson;
    private TextView tvTemNow,tvTemDay,tvWeather,tvFly,tvNewsTitle,tvNewsFrom,tvLookLife;
    private HomeNewsView homeNewsView;
    private GridView gridViewHandle,gridViewLife;
    private HomeHandleAdapter homeHandleAdapter;
    private HomeLifeAdapter homeLifeAdapter;
    private AMapLocation aMapLocation;//定位位置信息
    private String strCity;
    private HomeBean homeBean;
    private List<HomeNewsBean> newsList;
    private List<HandleThemeBean> themeBeanList;
    private List<LifeListBean> lifeList;

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if("refresh_home".equals(intent.getAction())){
                showLoadDialog();
                getData();
            }
        }
    };

    @Override
    protected View setView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fragment_home,null);
        hidenTop();
        return view;
    }

    @Override
    protected void initView() {
        refreshScrollView = (PullToRefreshScrollView) _rootView.findViewById(R.id.fg_home_scrollview);
        llLoc = (LinearLayout) _rootView.findViewById(R.id.fg_home_ll_loc);
        llHandle = (LinearLayout) _rootView.findViewById(R.id.fg_home_ll_handle);
        llDynamic = (LinearLayout) _rootView.findViewById(R.id.fg_home_ll_dynamic);
        llInteraction = (LinearLayout) _rootView.findViewById(R.id.fg_home_ll_interaction);
        llHelp = (LinearLayout) _rootView.findViewById(R.id.fg_home_ll_help);
        llNews = (LinearLayout) _rootView.findViewById(R.id.fg_home_ll_news);
        imgPerson = (ImageView) _rootView.findViewById(R.id.fg_home_img_person);
        tvTemNow = (TextView) _rootView.findViewById(R.id.fg_home_tv_tem_now);
        tvTemDay = (TextView) _rootView.findViewById(R.id.fg_home_tv_tem_day);
        tvWeather = (TextView) _rootView.findViewById(R.id.fg_home_tv_weather);
        tvFly = (TextView) _rootView.findViewById(R.id.fg_home_tv_fly);
        tvNewsTitle = (TextView) _rootView.findViewById(R.id.fg_home_tv_news_title);
        tvNewsFrom = (TextView) _rootView.findViewById(R.id.fg_home_tv_news_from);
        tvLookLife = (TextView) _rootView.findViewById(R.id.fg_home_tv_look_life);
        gridViewHandle = (GridView) _rootView.findViewById(R.id.fg_home_gridview_handle);
        gridViewLife = (GridView) _rootView.findViewById(R.id.fg_home_gridview_life);
        homeNewsView = (HomeNewsView) _rootView.findViewById(R.id.fg_home_news);

        llLoc.setFocusable(true);
        llLoc.setFocusableInTouchMode(true);
        llLoc.requestFocus();
    }

    @Override
    protected void initData() {
        newsList = new ArrayList<>();
        lifeList = new ArrayList<>();
        themeBeanList = new ArrayList<>();
        homeHandleAdapter = new HomeHandleAdapter(mContext,themeBeanList);
        homeLifeAdapter = new HomeLifeAdapter(mContext,lifeList);
        LocationManagers.getInstance().addListener(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction("refresh_home");
        mContext.registerReceiver(receiver,filter);
    }

    @Override
    protected void setListener() {
        super.setListener();
        llLoc.setOnClickListener(this);
        llHandle.setOnClickListener(this);
        llDynamic.setOnClickListener(this);
        llInteraction.setOnClickListener(this);
        llHelp.setOnClickListener(this);
        imgPerson.setOnClickListener(this);
        tvLookLife.setOnClickListener(this);
        gridViewHandle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent;
                if(position == themeBeanList.size()){
                    intent = new Intent(mContext, HandleSelectActivity.class);
                    intent.putExtra("list", (Serializable) homeBean.mythemeData);
                } else {
                    intent = new Intent(mContext, HandleListActivity.class);
                    intent.putExtra("theme_id",themeBeanList.get(position).theme_id);
                }
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(getActivity());
            }
        });

        gridViewLife.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext, LifeDetailActivity.class);
                intent.putExtra("life_id",lifeList.get(position).life_id);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(getActivity());
            }
        });
        refreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                showLoadDialog();
                getData();
            }
        });
    }

    @Override
    protected void fillData() {
        super.fillData();
        gridViewHandle.setAdapter(homeHandleAdapter);
        gridViewLife.setAdapter(homeLifeAdapter);
        newsList  = new ArrayList<>();
        homeNewsView.setList(newsList);
        if(MyApplication.aMapLocation != null){
            this.aMapLocation = MyApplication.aMapLocation;
            setLocation();
            showLoadDialog(1);
            getData();
        }
    }

    @Override
    public void doClick(View v) {
        super.doClick(v);
        Intent intent;
        switch (v.getId()){
            case R.id.fg_home_ll_loc://首页位置

                break;
            case R.id.fg_home_img_person://个人中心
                intent = new Intent(mContext,MineActivity.class);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(getActivity());
                break;
            case R.id.fg_home_ll_handle://我要办事
                intent = new Intent(StringConstants.MAIN_TAB_CHANGE_ACTION);
                intent.putExtra(StringConstants.TAB_INDEX, 1);
                mContext.sendBroadcast(intent);
                break;
            case R.id.fg_home_ll_dynamic://昌平动态
                intent = new Intent(mContext,DynamicHomeActivity.class);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(getActivity());
                break;
            case R.id.fg_home_ll_interaction://政民互动
                intent = new Intent(mContext,InteractionActivity.class);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(getActivity());
                break;
            case R.id.fg_home_ll_help://街道黄页
                intent = new Intent(mContext,HelpActivity.class);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(getActivity());
                break;
            case R.id.fg_home_tv_look_life://查看全部生活
                intent = new Intent(mContext,LifeMapActivity.class);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(getActivity());
                break;
        }
    }

    @Override
    public void locationChange() {
        this.aMapLocation = MyApplication.aMapLocation;
        setLocation();
        getData();
    }

    /** 设置位置信息*/
    public void setLocation(){
        strCity = aMapLocation.getDistrict();
        if(TextUtils.isEmpty(strCity)){
            strCity = aMapLocation.getCity();
        }

        WeatherSearchQuery mquery = new WeatherSearchQuery(strCity, WeatherSearchQuery.WEATHER_TYPE_LIVE);
        WeatherSearch mweathersearch=new WeatherSearch(mContext);
        mweathersearch.setOnWeatherSearchListener(this);
        mweathersearch.setQuery(mquery);
        mweathersearch.searchWeatherAsyn(); //异步搜索

        WeatherSearchQuery mquery2 = new WeatherSearchQuery(aMapLocation.getCity(), WeatherSearchQuery.WEATHER_TYPE_FORECAST);
        WeatherSearch mweathersearch2=new WeatherSearch(mContext);
        mweathersearch2.setOnWeatherSearchListener(this);
        mweathersearch2.setQuery(mquery2);
        mweathersearch2.searchWeatherAsyn(); //异步搜索

    }

    @Override
    public void onWeatherLiveSearched(LocalWeatherLiveResult weatherLiveResult, int rCode) {
        if (rCode == 1000) {
            if (weatherLiveResult != null && weatherLiveResult.getLiveResult() != null) {
                LocalWeatherLive weatherlive = weatherLiveResult.getLiveResult();
                LogUtil.e(weatherlive.getCity()+"  "+weatherlive.getWeather()+"---"+weatherlive.getTemperature()
                        +"  "+weatherlive.getWindDirection()+"  "+weatherlive.getWindPower());
                tvTemNow.setText(weatherlive.getTemperature());//温度
                tvWeather.setText(weatherlive.getWeather());//天气
                tvFly.setText(weatherlive.getWindDirection()+"风"+weatherlive.getWindPower()+"级");
            }else {
            }
        }
    }

    @Override
    public void onWeatherForecastSearched(LocalWeatherForecastResult localWeatherForecastResult, int rCode) {
        if (rCode == 1000) {
            LocalWeatherForecast weatherForecast = localWeatherForecastResult.getForecastResult();
            List<LocalDayWeatherForecast> list = weatherForecast.getWeatherForecast();
            tvTemDay.setText(list.get(0).getNightTemp()+"/"+list.get(0).getDayTemp()+"℃");
        }
    }

    private void getData(){
        RequestParams params = new RequestParams(Urls.url_home);
        params.addParameter("userid", DeviceInfo.getIMEI(mContext));
        postRequest(params, new RequestResultListener() {
            @Override
            public boolean onSuccess(BaseBean result) {
                refreshScrollView.onRefreshComplete();
                if(result.status == 1){
                    homeBean = gson.fromJson(result.data,HomeBean.class);
                    homeNewsView.setList(homeBean.todayData);
                    if(homeBean.mythemeData != null){
                        themeBeanList.clear();
                        themeBeanList.addAll(homeBean.mythemeData);
                        homeHandleAdapter.notifyDataSetInvalidated();
                    }
                    if(homeBean.lifeFourData != null){
                        lifeList.clear();
                        lifeList.addAll(homeBean.lifeFourData);
                        homeLifeAdapter.notifyDataSetChanged();
                    }
                }
                return false;
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                refreshScrollView.onRefreshComplete();
            }
        });
    }
}
